﻿using MediatR;
using NLog.Config;
using W.Device.Domain;
using W.Device.Domain.DTO;
using W.Purchase.Domain;
using W.Purchase.Domain.DTO;
using W.Purchase.Read.API.AppLication.Command;
using W.Purchase.Repository.Interface;

namespace W.Purchase.Read.API.AppLication.CommandHandler
{
    public class VendorShowCommandhandler : IRequestHandler<VendorShowCommand,List<VendorDTO>>
    {
        private readonly IVendorRepository vendorRepository;

        private readonly IVendorTypeRepository vendorTypeRepository;


        public VendorShowCommandhandler(IVendorRepository vendorRepository, IVendorTypeRepository vendorTypeRepository)
        {
            this.vendorRepository = vendorRepository;
            this.vendorTypeRepository = vendorTypeRepository;
        }

        public async Task<List<VendorDTO>> Handle(VendorShowCommand request, CancellationToken cancellationToken)
        {
            var list = from a in await vendorRepository.GetAllAsaync()
                       join b in await vendorTypeRepository.GetAllAsaync() on a.VendorTypeId equals b.VendorTypeId
                       where a.IsDelete == false
                       select new VendorDTO
                       {
                           VendorId=a.VendorId,
                           VendorNo= a.VendorNo,
                           VendorName= a.VendorName,
                           VendorState= a.VendorState,
                           VendorPhone= a.VendorPhone,
                           VendorFax= a.VendorFax,
                           VendorEmail= a.VendorEmail,
                           VendorContact=a.VendorContact,
                           VendorAddress= a.VendorAddress,
                           VendorDesc=a.VendorDesc,
                           VendorRemarks= a.VendorRemarks,
                           office_id= a.office_id,
                           user_id=a.user_id,
                           VendorTypeId = b.VendorTypeId,
                           VendorTypeName= b.VendorTypeName,
                           CreateTime= b.CreateTime
                       };
            if (request.VendorNo != "")
            {
                list = list.Where(w => w.VendorNo == request.VendorNo).ToList();
            }
            if (request.VendorName != "")
            {
                list = list.Where(w => w.VendorName.Contains(request.VendorName)).ToList();
            }
            if (request.VendorPhone != "")
            {
                list = list.Where(w => w.VendorPhone == request.VendorPhone).ToList();
            }
            if (request.VendorTypeId != 0)
            {
                list = list.Where(w => w.VendorTypeId == request.VendorTypeId).ToList();
            }
            return list.ToList();
        }
    }
}
